import {AsyncStorage} from 'react-native';
import * as request from "../utils/request";

const STORAGE_KEY = "STORAGE_KEY_mark";
export default {
    namespace: 'mark',
    state: {
        list: [],
        selectMarket: null,
    },
    reducers: {
        save(state, {payload}) {
            return Object.assign({}, state, payload);
        }
    },
    effects: {
        * saveToStorage({payload}, {call}) {
            yield call(AsyncStorage.setItem, STORAGE_KEY, JSON.stringify(payload));
        },
        * restoreFromStorage({payload}, {call, put, select}) {
            let data = yield call(AsyncStorage.getItem, STORAGE_KEY);

            data = JSON.parse(data);
            // yield put({
            //     type: 'save',
            //     payload: Object.assign({}, )
            // });


            if (!data) {
                yield put({
                    type: 'fetchList'
                })
            } else {

            }
            // if(Array.isArray(mark.list)){
            //
            // }
        },
        * fetchList({payload}, {call, put, select}) {
            const data = yield call(request.get, request.API.markList);
            if (data) {
                yield put({
                    type: 'save',
                    payload: {
                        list: data.data.map(item => (Object.assign({}, item, {
                            label: item.name,
                            value: item.id
                        })))
                    }
                });
                const mark = yield select(state => state.mark);
                yield put({
                    type: 'saveToStorage',
                    payload: {...mark}
                })
            }
        },

        * selectMarket({payload}, {put,select}) {
            yield put({
                type:'save',
                payload:{selectMarket:{...payload}}
            });
            const mark = yield select(state => state.mark);
            yield put({
                type: 'saveToStorage',
                payload: {...mark}
            })

        },
    },
    subscriptions: {
        setup({dispatch}) {
            dispatch({
                type: 'restoreFromStorage'
            })
        }
    },
};
